package designpatterns.observer;

public class ConcreteSubject extends Subject {
    private int state;

    @Override
    public void attach(Observer observer) {
        if(!this.observers.contains(observer)) {
            this.observers.add(observer);
        }
    }

    @Override
    public void detach(Observer observer) {
        if(this.observers.contains(observer)) {
            this.observers.remove(observer);
        } else {
            System.out.println("指定的观察者不存在");
        }
    }

    @Override
    public void notifyOb() {
        for(Observer ob: observers) {
            ob.update(state);
        }
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    // 业务逻辑方法
    public void service() {
        System.out.println("处理一些业务逻辑...");
        // 然后改变了状态
        for (int i = 0; i < 5; i++) {
            this.state = i * 2;
            // 观察目标通知观察者
            this.notifyOb();
        }
        System.out.println("完成处理");
        this.state = -1; // 这里约定 -1 表示完成
        this.notifyOb();
    }
}
